﻿using System.Collections;
using System.Collections.Generic;
using com.guojin.mj.net.message.game;
using UnityEngine;
using UnityEngine.UI;

public class Player : MonoBehaviour
{

    public string avatar;
    private int betScore;

    private readonly List<int> handCardsList = new List<int>();

    public Texture headTexture; //玩家头像暂存
    public string ip;
    public bool isMiddleJoin;
    public bool isOut;
    public bool isVoteResult;//是不是投过解散房间的票
    public string latitude;
    public int locationIndex;
    public string longitude;
    public GameObject playerHeadObj;
    public GameObject playerCardObj;
    public GameObject readyObj;
    public int roomCard;
    public int sex;
    public string AllCardType;//全部开牌分数
    public string ShowCardType;//临时开牌分数

    public string userName;
    public int userId;
    public bool VoteResult;
    public int winCounts;
    public int defeatCounts;

    #region    //自动属性
    private bool isReady;
    private bool online;
    private bool isTrusteeship;//自动托管
    private int betState;
    private int playerState;                                 // 0无状态   1赢家  2输家 3聚锅  4弃牌
    private int userTotalScore;
    private bool isSelect;

    public bool IsSelect
    {
        get { return isSelect; }
        set
        {
            isSelect = value;
            ChangeSelect(isSelect);
        }
    }
    public bool IsReady
    {
        get { return isReady; }
        set
        {
            isReady = value;
            ChangeReady(isReady);
        }
    }

    public bool Online
    {
        get { return online; }
        set
        {
            online = value;
            ChangeOutLine(online);
        }
    }
    public bool IsTrusteeship
    {
        get { return isTrusteeship; }
        set
        {
            isTrusteeship = value;
            ChangeTrusteeShip(isTrusteeship);
        }
    }
    public int BetState
    {
        get { return betState; }
        set { betState = value; }
    }
    public int PlayerState
    {
        get { return playerState; }
        set
        {
            playerState = value;
            ChangePlayerState(playerState);
        }
    }
    public int UserTotalScore
    {
        get { return userTotalScore; }
        set
        {
            userTotalScore = value;
            ChangeTotalScore(userTotalScore);
        }
    }
    #endregion

    #region//初始化玩家信息
    public void InitPlayerUserInfo(GameUserInfoRet GameUser)                       //初始化玩家头像信息
    {
        SetReferenceToObj();
        SaveUserInfoToThis(GameUser);
        playerHeadObj.GetComponent<PlayerHeadController>().InitPlayerHead(GameUser);
        SetCardGroupOwnLocationIndex();
    }

    private void SetReferenceToObj()
    {
        playerHeadObj = gameObject;
        playerCardObj = playerHeadObj.transform.parent.parent.FindChild("cardPoint/playerCard").gameObject;
        readyObj = playerHeadObj.transform.parent.parent.FindChild("ready").gameObject;
    }

    private void SaveUserInfoToThis(GameUserInfoRet GameUser)
    {
        userName = GameUser.userName;
        avatar = GameUser.avatar;
        sex = GameUser.sex;
        roomCard = GameUser.roomCard;
        UserTotalScore = GameUser.totalScore;
        locationIndex = GameUser.locationIndex;
        userId = GameUser.userId;
        ip = GameUser.ip;
        isMiddleJoin = GameUser.isMiddleJoin;
        IsReady = GameUser.isReady;
        Online = GameUser.online;
        IsTrusteeship = GameUser.isTrusteeship;
        longitude = GameUser.longitude;
        latitude = GameUser.latitude;
        if (isMiddleJoin)
        {
            isOut = true;
        }

        if (locationIndex != GameData.GetInstance().locationIndex)
        {
            playerCardObj.transform.FindChild("cardType").GetComponent<Text>().color = Color.white;
        }
    }

    private void SetCardGroupOwnLocationIndex()
    {
        playerCardObj.transform.FindChild("cardGroup").gameObject.GetComponent<PlayerCardController>().ownPlayerLocationIndex =
            locationIndex;
    }

    public void InitPlayerChapterInfo(UserChapterInfoRet ucir)    //初始化玩家牌局信息（断线重连使用）
    {
        #region   //打印收到的玩家信息
        Debug.Log("玩家：" + ucir.LocationIndex);
        Debug.Log("手牌为：");
        foreach (var item in ucir.Cards)
            Debug.Log(item + ", ");
        Debug.Log("总分数为：" + ucir.UserTotalScore);
        Debug.Log("五张牌型为：+" + ucir.AllCardType);
        Debug.Log("亮牌牌型为：+" + ucir.ShowCardType);
        Debug.Log(string.Format("玩家状态为：+" + ucir.BetState));

        #endregion
        UserTotalScore = ucir.UserTotalScore;
        AllCardType = ucir.AllCardType;
        ShowCardType = ucir.ShowCardType;
        BetState = ucir.BetState;
        winCounts = ucir.WinCounts;
        defeatCounts = ucir.DefeatCounts;

        BreakOnlineAddCard(ucir.Cards);

        if (betState == 5)
        {
            isOut = true;
            PlayerState = 4;
        }

        if (GameRoomModel.GetInstance().RoomState == 1)
        {
            ShowShowCardType();
        }
        else
        {
            ShowAllCardType();
        }
    }

    public void InitBetState()                               //每次发牌，清空玩家的下注状态
    {
        BetState = 0;
    }
    #endregion

    #region  //玩家的自动属性(状态, 分数)改变方法

    //public void ChangePlayerState()
    //{
    //    var temp = GetShowState();
    //    playerHeadObj.GetComponent<PlayerHeadController>().SetPlayerHeadState(temp);
    //}
    //private  string GetShowState()                          //如果有玩家状态（托管，离线，准备）优先显示玩家状态，没有则显示下注状态
    //{
    //    string temp = null;

    //    if (!string.IsNullOrEmpty(GetUserState()))
    //    {
    //        temp = GetUserState();
    //        return temp;
    //    }

    //    if (!string.IsNullOrEmpty(GetBetState()))
    //    {
    //        temp = GetBetState();
    //        return temp;
    //    }

    //    return temp;
    //}
    //private string GetUserState()
    //{
    //    string temp = null;

    //    if (IsTrusteeship)
    //        temp = "托管";
    //    else if (!Online)
    //        temp = "离线";
    //    else if (IsReady)
    //        temp = "准备";
    //    return temp;
    //}
    //private string GetBetState()
    //{
    //    string temp = null;
    //    switch (BetState)
    //    {
    //        case 1:
    //            temp = "下注中";
    //            break;
    //        case 2:
    //            temp = "下注完成";
    //            break;
    //        case 3:
    //            temp = "跟注中";
    //            break;
    //        case 4:
    //            temp = "跟注完成";
    //            break;
    //        case 5:
    //            temp = "弃牌";
    //            break;
    //        default:
    //            break;
    //    }
    //    return temp;
    //}

    private void ChangeSelect(bool isSelect)
    {
        if (isSelect)
        {
            foreach (var item in GameRoomModel.GetInstance().playerDic.Values)
            {
                if (item.IsSelect)
                {
                    item.IsSelect = false;
                }
            }
            playerHeadObj.GetComponent<PlayerHeadController>().SetSelect(true);
        }
        else
        {
            playerHeadObj.GetComponent<PlayerHeadController>().SetSelect(false);
        }
    }

    private void ChangeTrusteeShip(bool isTrusteeship)
    {
        if (isTrusteeship)//修改托管头像图片
        {
            playerHeadObj.GetComponent<PlayerHeadController>().SetTrusteeship(true);
            if (locationIndex == GameData.GetInstance().locationIndex)
            {
                UIManager.ChangeUI(UIManager.PageState.TrusteeShipPage, (GameObject obj) =>
                {
                    obj.GetComponent<TruesteeShipPage>().InformationSetting();
                });
            }
        }
        else
        {
            playerHeadObj.GetComponent<PlayerHeadController>().SetTrusteeship(false);
            if (GameObject.Find("TrusteeShipPage(Clone)"))//托管界面有
            {
                if (locationIndex == GameData.GetInstance().locationIndex)
                {
                    GameObject.Find("TrusteeShipPage(Clone)").gameObject.GetComponent<TruesteeShipPage>().CloseBtnClick();
                }
            }
        }
    }

    private void ChangeOutLine(bool Online)
    {
        if (!Online)
        {
            playerHeadObj.GetComponent<PlayerHeadController>().SetOutline(true);
        }
        else
        {
            playerHeadObj.GetComponent<PlayerHeadController>().SetOutline(false);
        }
    }

    private void ChangeReady(bool isReady)
    {
        if (isReady)
        {
            readyObj.SetActive(true);
        }
        else
        {
            readyObj.SetActive(false);
        }
    }

    private void ChangePlayerState(int state)             // 0无状态   1赢家  2输家 3聚锅  4弃牌
    {
        switch (state)
        {
            case 0:
                playerHeadObj.GetComponent<PlayerHeadController>().SetPlayerHeadState(string.Empty);
                break;
            case 1:
                playerHeadObj.GetComponent<PlayerHeadController>().SetPlayerHeadState("大赢家");
                break;
            case 2:
                playerHeadObj.GetComponent<PlayerHeadController>().SetPlayerHeadState("输牌");
                break;
            case 3:
                playerHeadObj.GetComponent<PlayerHeadController>().SetPlayerHeadState("聚锅");
                break;
            case 4:
                playerHeadObj.GetComponent<PlayerHeadController>().SetPlayerHeadState("弃牌");
                break;
        }
    }

    private void ChangeTotalScore(int totalSocre)
    {
        playerHeadObj.GetComponent<PlayerHeadPage>().SetTotalScoreText(totalSocre);
    }

    public void PlayStateAni(string str)
    {
        playerCardObj.GetComponent<PlayerCardPage>().PlayPlayerStateAni(str);
    }

    public void SetDownTime(bool show, int time)
    {
        playerHeadObj.GetComponent<PlayerHeadController>().SetDownTime(show, time);
    }

    #endregion

    #region  //点击ReadyBtn玩家初始化方法
    public void ClickReadyInitUser()
    {
        ClearHandCardsList();
        ClearHandCardsObj();
        ClearPlayerCardType();
        ClearPlayerState();
        SetPlayerCardIsShowFalse();
    }
    private void ClearHandCardsList()
    {
        //初始化手牌列表
        handCardsList.Clear();
    }
    private void ClearHandCardsObj()
    {
        handCardsList.Clear();

        if (playerCardObj.transform.FindChild("cardGroup").childCount != 0)
            TooL.DestroyAllChildren(playerCardObj.transform.FindChild("cardGroup").gameObject); //清空手牌(每次发牌都)
    }
    private void ClearPlayerCardType()
    {
        playerCardObj.GetComponent<PlayerCardPage>().SetCardType(null);
    }

    private void ClearPlayerState()
    {
        PlayerState = 0;
    }

    private void SetPlayerCardIsShowFalse()
    {
        playerCardObj.transform.FindChild("cardGroup").gameObject.GetComponent<PlayerCardController>().isShowCard =            false;
    }
    #endregion

    #region//添加手牌
    public void AddCard(int cards)
    {
        AddCardsToHandCardsList(cards);
        AddCardsObjToCardGroup(cards);
    }

    private void AddCardsToHandCardsList(int cards)
    {
        handCardsList.Add(cards);
    }

    private void AddCardsObjToCardGroup(int cards)
    {
        var temp = TooL.DealHandCardAni(playerCardObj.transform.FindChild("cardGroup").gameObject, "Card");
        temp.GetComponent<Card>().cardValue = cards;
        temp.name = cards.ToString();
        CardLoadValueOrBack(temp);
    }

    private void CardLoadValueOrBack(GameObject temp)
    {
        Transform group = playerCardObj.transform.FindChild("cardGroup");

        if (GameRoomModel.GetInstance().RoomState == 1)            // 房间状态1 只有前两张并且没有点击开显示背面
        {
            if (group.childCount < 3 && group.GetComponent<PlayerCardController>().isShowCard == false)
            {
                temp.GetComponent<Card>().LoadBackSprite();
                Debug.Log("背牌" + temp.name);

                temp.GetComponent<Card>().hideCard = true;
            }
            else
            {
                temp.GetComponent<Card>().LoadValueSprite();
                Debug.Log("牌面" + temp.name);
                temp.GetComponent<Card>().hideCard = false;
            }
        }
        else if (GameRoomModel.GetInstance().RoomState == 2)      //房间状态2只有弃牌 前两张显示背面
        {
            if (BetState == 5 && group.childCount < 3)
            {
                Debug.Log("背牌");

                temp.GetComponent<Card>().LoadBackSprite();
                temp.GetComponent<Card>().hideCard = true;
            }
            else
            {
                temp.GetComponent<Card>().LoadValueSprite();
                temp.GetComponent<Card>().hideCard = false;
            }
        }
    }

    public void BreakOnlineAddCard(int[] cards)
    {
        BreakOnlineAddCardsToHandCardsList(cards);
        BreakOnlineAddCardsObjToCardGroup(cards);
    }

    private void BreakOnlineAddCardsToHandCardsList(int[] cards)
    {
        for (int i = 0; i < cards.Length; i++)
        {
            handCardsList.Add(cards[i]);
        }
    }

    private void BreakOnlineAddCardsObjToCardGroup(int[] cards)
    {
        for (int i = 0; i < cards.Length; i++)
        {
            var temp = TooL.LoadPrefab(playerCardObj.transform.FindChild("cardGroup").gameObject, "Card");
            temp.GetComponent<Card>().cardValue = cards[i];
            temp.name = cards[i].ToString();
            temp.GetComponent<LayoutElement>().ignoreLayout = false;
            CardLoadValueOrBack(temp);
        }
    }
    #endregion

    #region //亮牌
    public void ShowCard()
    {
        //    if (GameRoomModel.GetInstance().isfinishGame) //完成游戏所有人的牌和分都显示出来
        //    {
        //        if (!isOut)//弃牌的人不变
        //        {
        //            var temp = playerCardObj.transform.FindChild("cardGroup");
        //            GameRoomPage.GetInstance().SetAudAndPlay(4);

        //            for (var i = 0; i < temp.childCount; i++)
        //                if (i < 2)
        //                    temp.GetChild(i).GetComponent<Card>().LoadValueSprite();
        //        }
        //    }
        //    else
        //    {
        if (!isOut)
            {
                var temp = playerCardObj.transform.FindChild("cardGroup");
                GameRoomPage.GetInstance().SetAudAndPlay(4);

                for (var i = 0; i < temp.childCount; i++)
                    if (i < 2)
                        temp.GetChild(i).GetComponent<Card>().LoadValueSprite();
            }
        //}

    }

    public void ShowAllCardType()
    {
        playerCardObj.GetComponent<PlayerCardPage>().SetCardType(AllCardType);//全部开牌分数
    }

    public void ShowShowCardType()
    {
        if (playerCardObj.transform.FindChild("cardGroup").gameObject.GetComponent<PlayerCardController>().isShowCard == true)
        {
            playerCardObj.GetComponent<PlayerCardPage>().SetCardType(AllCardType);
        }
        else
        {
            playerCardObj.GetComponent<PlayerCardPage>().SetCardType(ShowCardType);
        }
    }
    #endregion

    #region 玩家下注动画
    public void PlayerBet(int betNum)
    {
        GameController.GetInstance().InstantiateAddBetCircleAndDOTween(betNum.ToString(), playerHeadObj.transform, 0.9f);
        UserTotalScore -= betNum;
        GameRoomModel.GetInstance().CurrentTotalBet += betNum;
    }

    //老的下注方法，客户该需求暂时不用
    //public void PlayerBetNum(int betNum)
    //{
    //    var temp = CalculateBetMethod(betNum, 20);
    //    temp = CalculateBetMethod(temp, 10);
    //    temp = CalculateBetMethod(temp, 5);
    //    temp = CalculateBetMethod(temp, 2);
    //    temp = CalculateBetMethod(temp, 1);
    //}

    //private int CalculateBetMethod(int betNum, int remainderNum)
    //{
    //    if (betNum != 0)
    //    {
    //        var temp = betNum/remainderNum;

    //        if (temp != 0)
    //        {
    //            for (var i = 0; i < temp; i++)
    //                PlayerBetAni(remainderNum);

    //            betNum -= temp*remainderNum;
    //        }
    //    }
    //    return betNum;
    //}

    //private void PlayerBetAni(int num)
    //{
    //    switch (num)
    //    {
    //        case 1:
    //            GameController.GetInstance().InstantiateAddBetCircleAndDOTween("1", playerHeadObj.transform, 1.2f);
    //            break;
    //        case 2:
    //            GameController.GetInstance().InstantiateAddBetCircleAndDOTween("2", playerHeadObj.transform, 1.2f);
    //            break;
    //        case 5:
    //            GameController.GetInstance().InstantiateAddBetCircleAndDOTween("5", playerHeadObj.transform, 1.2f);
    //            break;
    //        case 10:
    //            GameController.GetInstance().InstantiateAddBetCircleAndDOTween("10", playerHeadObj.transform, 1.2f);
    //            break;
    //        case 20:
    //            GameController.GetInstance().InstantiateAddBetCircleAndDOTween("20", playerHeadObj.transform, 1.2f);
    //            break;
    //    }
    //}        
    #endregion

    //退出房间删除头像
    public void ExitRoomDeleteHead()
    {
        Destroy(playerHeadObj.gameObject);
        Destroy(playerCardObj.gameObject);
    }
}